﻿using KingerRobot.PCRBW.Spi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace KingerRobot.PCRBW.SpiService;

public class SlibeTableImpl: ISlibeTableService
{
    private readonly static ITaskService _taskService = new WcsTaskImpl();
    private readonly static IMesProductService _mesProductService = new MesProductImpl();

    public MesProductTask CreateTask(string equipName, int source_type)
    {
        return _taskService.CreateSlibeTableTask(equipName, source_type);
    }

    #region 任务执行
    /// <summary>
    /// 任务执行
    /// </summary>
    /// <param name="taskNo">任务号</param>
    /// <param name="locId">库位</param>
    /// <returns>-1未查询到任务 1任务更改成功；0 当前任务没有是创建的</returns>
    public int ExecuteTask(int taskNo, long locId)
    {
        // 更新任务指令状态
        int result = _taskService.UpdateTaskAndCmdStatus(locId, taskNo, (int)EnumTaskCmdStatus.Executed);
        if (result > 0)
        {
            return 1;
        }
        return -1;
    }

    #endregion

    public int FinishTask(int taskNo)
    {
        Expression<Func<POWcsTask, bool>> whereExpression = x => true;
       
        whereExpression = whereExpression.And(d => d.TaskNo == taskNo && d.TaskStatus !=(int)EnumTaskStatus.Finish);
        var task = _taskService.QueryFrist(whereExpression);
        if (task is null || task.Task == null || task.Cmd == null)
        {
            WriteLog($"未查询到任务，任务号:[{taskNo}]", true);
            return -9;
        }
        // 修改任务状态
        
        int result=_mesProductService.UpdateByStatus(new MesProduct() { Id= task.Task.MesId,Status=5});
        result= _taskService.UpdateTaskAndCmdStatus(task.Task.TargetLoc.GetValueOrDefault(), task.Task.TaskNo.GetValueOrDefault(), (int)EnumTaskStatus.Finish);
        return result;
    }

    /// <summary>
    /// 删除任务
    /// </summary>
    /// <param name="taskNo"></param>
    /// <returns></returns>
    public int DeleteTask(string equipName)
    {
        int result = 0;
        Expression<Func<POWcsTask, bool>> whereExpression = x => true;

        var mesProduct = _mesProductService.QueryByEquipName(equipName);
        if (mesProduct is null)
        {
            WriteLog($"未查询到产出任务，设备名称:[{equipName}]");
            return -9;
        }

        whereExpression = whereExpression.And(d =>d.TaskStatus == (int)EnumTaskStatus.Executed  && d.TaskType==(int)EnumTaskType.SlibeTable && d.MesId== mesProduct.Id);
        var task = _taskService.QueryFrist(whereExpression);
        if (task is null || task.Task == null || task.Cmd == null)
        {
            WriteLog($"未查询到任务，设备任务号:[{equipName}]");
            return -9;
        }
        // 删除任务状态

        result= _mesProductService.DeleteByTask(mesProduct, task.Task, task.Cmd);
        if (result<=0)
        {
            WriteLog($"删除任务失败，返回值:[{result}]");
            return -8;
        }

        return result;
    }
}
